package unit17.post;

import java.awt.image.RescaleOp;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
public class PostTest {
	public static void main(String[] args) throws IOException {
		Properties props=new Properties();
		try(InputStream in=Files.newInputStream(Paths.get(args[0]))){
			props.load(in);
		}
		String url=props.remove("url").toString();
		String result=doPost(url,props);
		System.out.println(result);
	}

	private static String doPost(String url, Map<Object, Object> props) throws IOException {
		// TODO Auto-generated method stub
		URL url2=new URL(url);
		URLConnection connection=url2.openConnection();
		connection.setDoOutput(true);
		
		try(PrintWriter out=new PrintWriter(connection.getOutputStream())){
			boolean first=true;
			
			for(Map.Entry<Object, Object> pair:props.entrySet()){
				if(first){
					first=false;
				}else{
					out.println('&');
				}
				String name=pair.getKey().toString();
				String value=pair.getValue().toString();
				out.print(name);
				out.print('=');
				out.print(URLEncoder.encode(value,"UTF-8"));
			}
		}
		StringBuffer reponse=new StringBuffer();
		try(Scanner in=new Scanner(connection.getInputStream())){
			while(in.hasNextLine()){
				reponse.append(in.nextLine());
				reponse.append("\n");
			}
		}catch (Exception e) {
			// TODO: handle exception
			if(!(connection instanceof HttpURLConnection)){
				throw e;
			}
			InputStream err=((HttpURLConnection)connection).getErrorStream();
			if(err==null) throw e;
			Scanner in=new Scanner(err);
			reponse.append(in.nextLine());
			reponse.append("\n");
		}
		return reponse.toString();
	}
}
